/*
 * Copyright (c) 2021 Zsj. All rights reserved.
 */

package com.jzz.crawlerweb.handler.generator;

import com.jzz.crawlerweb.handler.generator.impl.DefaultBackgroundImageHandler;
import com.jzz.crawlerweb.handler.generator.impl.DrawTextImageHandler;
import com.jzz.crawlerweb.handler.generator.impl.NoiseImageHandler;
import com.jzz.crawlerweb.handler.generator.impl.TwistImageHandler;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 文本型验证码渲染器
 */
public class TextCaptchaGenerator {
    private final int width = 240;
    private final int height = 80;
    private final int fontSize = 60;
    private String text;
    private List<ImageHandler> imageHandlers = new ArrayList<>();

    public TextCaptchaGenerator() {
        imageHandlers.add(new DrawTextImageHandler());
        imageHandlers.add(new NoiseImageHandler());
        imageHandlers.add(new TwistImageHandler());
        imageHandlers.add(new DefaultBackgroundImageHandler());
    }

    public TextCaptchaGenerator(String text) {
        this();
        this.text = text;
    }

    public TextCaptchaGenerator(String text, List<ImageHandler> imageHandlers) {
        this.text = text;
        this.imageHandlers = imageHandlers;
    }

    public BufferedImage render() {
        if (text == null) {
            return null;
        }

        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (ImageHandler handler : imageHandlers) {
            bi = handler.handle(bi, text, fontSize, 4);
        }
        return bi;
    }

    public byte[] renderBytes() {
        BufferedImage bi = render();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(bi, "jpg", baos);
        } catch (IOException e) {
            e.printStackTrace();
            return new byte[0];
        }
        return baos.toByteArray();
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public List<ImageHandler> getImageHandlers() {
        return imageHandlers;
    }

    public void setImageHandlers(List<ImageHandler> imageHandlers) {
        this.imageHandlers = imageHandlers;
    }
}
